%% Author: kevin.jingqiu
%% Created: May 29, 2009
%% Description: Find Pythagorean triplet {a, b, c} such that a+b+c=1000
-module(p9).

%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([solve/0, is_sum_to/2]).

%%
%% API Functions
%%
solve() ->
	[A, B, C] = p9([{A,B} || A<-lists:seq(1,1000), B<-lists:seq(1,1000)]),
	A*B*C.



%%
%% Local Functions
%%
p9([H|T]) ->
	case p9(H) of
		{ok, L} -> L;
		{fail, _} -> p9(T)
	end;


p9({A,B}) ->
	case comp_c(A, B) of
		{ok, C} ->
			case is_sum_to([A, B, C], 1000) of
				true -> {ok, [A, B, C]};
				false -> {fail, []}
			end;
		{fail, _} -> {fail, []}
	end.

%%
comp_c(A, B) ->
	C = math:sqrt(A*A + B*B),
	case mylib:is_actual_integer(C) of
		true ->
			{ok, trunc(C)};
		false ->
			{fail, []}
	end.

%% Test if the sum of list is exactly Sum
is_sum_to(List, Sum) ->
	case lists:sum(List) =:= Sum of
		true -> true;
		_ -> false
	end.



